/* 
 * @author Тарас Куньч <taras.kunch@gmail.com>
 */
var TicTacToe = (function($){
   var staticCellWidth = 50, staticUid = -1;
   var __construct = function(conatainer, cells){
      var instance = $('<div class="tic-tac-toe">').css("width", cells*staticCellWidth+'px');
      var uid = ++staticUid;
      var cell = undefined;
      var lastMark = 0;

      var getMark = function(){
         lastMark = !lastMark;
         return (lastMark == 1)?'cross':'circle';
      };
      var onClick = function(){
         if ($(this).hasClass(getMark()) || $(this).hasClass(getMark())){
            return;
         }
         var posX = $(this).attr("posX");
         var posY = $(this).attr("posY");
         var id = 0;
         if (!wave.getState().get('id')){
            id = 1;
         } else {
            id = parseInt(wave.getState().get('id'));
         }
         var delta = {'id':(id + 1)};
         delta[id] = posX+'|'+posY;
         wave.getState().submitDelta(delta);
      };

      instance.append($('<div class="top left" posX="1" posY="1">'));
      for(var i = 2; i <= cells - 1; ++i) instance.append($('<div class="top" posX="'+i+'" posY="1">'));
      instance.append($('<div class="top right" posX="'+cells+'" posY="1">'));
      for(var i = 2; i <= cells - 1; ++i){
         instance.append($('<div class="left" posX="1" posY="'+i+'">'));
         for(var j = 2; j <= cells - 1; j++) instance.append($('<div posX="'+j+'" posY="'+i+'">'));
         instance.append($('<div class="right" posX="'+cells+'" posY="'+i+'">'));
      }
      instance.append($('<div class="bottom left" posX="1" posY="'+cells+'">'));
      for(var i = 2; i <= cells - 1; ++i) instance.append($('<div class="bottom" posX="'+i+'" posY="'+cells+'">'));
      instance.append($('<div class="bottom right" posX="'+cells+'" posY="'+cells+'">'));
      instance.find('div').click(onClick);
      $(conatainer).append(instance);
      gadgets.window.adjustHeight();

      this.setMark = function(xy){
         var pos = xy.split('|');
         var cell = instance.find('[posX='+pos[0]+'][posY='+pos[1]+']');
         if (!cell.hasClass(getMark()) && !cell.hasClass(getMark())){
            cell.addClass(getMark());
         }
      };
   };
   return __construct;
})(jQuery);
var sizeX = 3;
var instance = undefined;
var lastId = 1;
var renderInfo = function(){
   if(wave.getState().get('id')) {
      for(var i = lastId; i < wave.getState().get('id'); ++i){
         instance.setMark(wave.getState().get(i+''));
         if ((i % (sizeX*sizeX))==0){
            instance = new TicTacToe('.game_container', sizeX);
         }
      }
      lastId = wave.getState().get('id');
   }
};

function init() {
   if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(renderInfo);
   }
   instance = new TicTacToe('.game_container', sizeX);
}
gadgets.util.registerOnLoadHandler(init);